<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户">
        <!-- <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable size="small">
          <el-option
            v-for="dict in userOption"
            :key="dict.guid"
            :label="dict.realname"
            :value="dict.guid"
          />
        </el-select> -->
        <el-input
          v-model="queryParams.searchName"
          placeholder="请输入用户或者电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="正常" value="1" />
          <el-option label="失效" value="2" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="组织" prop="orgid">
        <el-select v-model="queryParams.orgid" @change="takeOrg" placeholder="请选择组织" clearable size="small">
          <el-option
            v-for="dict in orgs"
            :key="dict.guid"
            :label="dict.name"
            :value="dict.guid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库房" prop="srguid">
        <el-select v-model="queryParams.srguid" placeholder="请选择库房" clearable size="small">
          <el-option
            v-for="dict in storeroomOption"
            :key="dict.guid"
            :label="dict.name"
            :value="dict.guid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <treeselect style="width: 297px;" v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择部门" />
<!--        <el-select v-model="queryParams.deptId" placeholder="请选择部门" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="dict in departOption"-->
<!--            :key="dict.guid"-->
<!--            :label="dict.name"-->
<!--            :value="dict.guid"-->
<!--          />-->
<!--        </el-select>-->
      </el-form-item>
      <el-form-item label="权限" prop="permission">
        <el-select v-model="queryParams.permission" placeholder="请选择权限" clearable size="small"
           filterable
           remote
           :remote-method="remoteMethod"
           :loading="loading2"
        >
          <el-option
            v-for="dict in permisOptions"
            :key="dict.code"
            :label="dict.name"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['permission:salespermission:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['permission:salespermission:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['permission:salespermission:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['permission:salespermission:export']"
        >导出</el-button>
      </el-col> -->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="salespermissionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户" align="center" prop="realName" >
        <template slot-scope="scope">
          <span>{{scope.row.realName + '-' + scope.row.telphone}}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限" align="center" prop="permissiontext" width="100" />
      <el-table-column label="组织" align="center" prop="orgName" />
      <el-table-column label="部门" align="center" prop="depName" />
      <el-table-column label="库房" align="center" prop="storeName" />
      <el-table-column label="状态" align="center" prop="status" width="60">
        <template slot-scope="scope">
           <span v-if="scope.row.status == 1">正常</span>
            <span v-if="scope.row.status == 2">失效</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createtime" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="60">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['permission:salespermission:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['permission:salespermission:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改权限管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请输入并选择用户" remote :remote-method="userList" :loading="remoteLoading" clearable filterable>
          <el-option
            v-for="dict in userOption"
            :key="dict.userId"
            :label="dict.nickName + dict.phonenumber"
            :value="dict.userId"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
              @click.native="getPre($event, dict)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId" v-if="departShow">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item v-if="[1,3,7].includes(form.type)" label="组织" prop="orgid">
          <el-select v-model="form.orgid" @change="takeOrg2" placeholder="请选择组织" clearable>
            <el-option
              v-for="dict in orgs"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库房" prop="srguid" v-if="srShow">
          <el-select v-model="form.srguid" placeholder="请选择库房" clearable>
          <el-option
            v-for="dict in storeroomOption2"
            :key="dict.guid"
            :label="dict.name"
            :value="dict.guid"
             @click.native="getdefBySr($event, dict)"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="permission" v-if="permissionShow">
          <!-- <el-input v-model="form.permission" placeholder="请输入权限" /> -->
          <el-checkbox-group v-model="permissions">
            <el-checkbox  v-for="i in permissionOptions" :label="i" :key="i.code" >{{i.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeselect } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { listSalespermission, getSalespermission, delSalespermission, addSalespermission, updateSalespermission, exportSalespermission } from "@/api/permission/salespermission";
import { getPermissionDeflist, findStoreroom, tuserList, getDepartmentList, getSRoomByOrgId, getOrgs } from "@/api/public";
import { listDept } from "@/api/system/dept";
import { getDictEmnu } from "@/api/permission/permissiondef";
import { listOrgs } from "@/api/organization/organization";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Salespermission",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 权限管理表格数据
      salespermissionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        status: null,
        orgid: null,
        srguid: null,
        deptId: null
      },
      // 表单参数
      form: {
        userId: '',
        deptId: ''
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户不能为空", trigger: "blur" }
        ],
        permissions: [
          { required: true, message: "权限不能为空", trigger: "blur" }
        ],
      },
      permissionDef: [],
      departOption: [],
      storeroomOption: [],
      storeroomOption2: [],
      userOption: [],
      departShow: false,
      srShow:false,
      permissionShow: false,
      permissionOptions: [],
      permissions : [],
      deptOptions: [],
      orgs: [],
      permisOptions: [],
      remoteLoading: false
    };
  },
  created() {
    this.getPermissionDeflist();
    this.getDepartmentList();
    this.getOrgs();
    // this.userList();
    this.getList();
    this.getTreeselect();
    this.getDicts("scope_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  watch: {
    'form.deptId': function(val) {
      this.getdefByDepart(val);
    }
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.loading2 = true;
        setTimeout(() => {
          this.loading2 = false;
          this.permisOptions = this.permissionDef.filter(item => {
            return item.name.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.permisOptions = this.permissionDef;
      }
    },
    getdefByDepart(deptId){
      if (!deptId) return;
      let params = {};
      params.departid = deptId;
      params.type = this.form.type
      params.userguid = this.form.userId
      getDictEmnu(params).then(response => {
        this.permissionOptions = response.data;
        console.log(this.permissionOptions)
        this.permissionShow = true;
      });
    },
    takeOrg(val) {
        this.findStoreroom(val);
        this.queryParams.srguid = '';
    },
    takeOrg2(val) {
      if (this.form.type == 1) {
        this.getdefByOrg();
      }
      if (this.form.type == 3 || this.form.type == 7) {
        let orgGuid = this.orgs.find(item => item.id == val).guid;
        this.form.srguid = '';
        this.findStoreroom2(orgGuid);
      }
    },
    getDepartmentList(){
      listDept().then(response => {
        this.departOption = response.data;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    getdefBySr(event, item){
      console.log(item)
        let params = {};
        params.srguid = item.guid;
        params.type = this.form.type
        params.userguid = this.form.userId
        getDictEmnu(params).then(response => {
          this.permissionOptions = response.data;
          console.log(this.permissionOptions)
          this.permissionShow = true;
        });
    },
    getdefByOrg(){
      let params = {};
      params.orgid = this.form.orgid
      params.type = this.form.type
      params.userguid = this.form.userId
      getDictEmnu(params).then(response => {
        this.permissionOptions = response.data;
        console.log(this.permissionOptions)
        this.permissionShow = true;
      });
    },
    getPre(event, item){
      if(item.dictValue == 1){
        this.srShow = false;
        this.departShow = false;
        this.permissionShow = false;
      }
      if(item.dictValue == 2){
        this.srShow = false;
        this.departShow = true;
        this.permissionShow = false;
      }
      if(item.dictValue == 3){
        this.srShow = true;
        this.departShow = true;
        this.permissionShow = false;
      }
      if(item.dictValue == 4){
        this.srShow = false;
        this.departShow = false;
        this.permissionShow = true;
         let params = {};
        params.type = this.form.type
        getDictEmnu(params).then(response => {
          this.permissionOptions = response.data;
          console.log(this.permissionOptions)
          this.permissionShow = true;
        });
      }
      if(item.dictValue == 5){
        this.srShow = false;
        this.departShow = false;
        this.permissionShow = true;
         let params = {};
        params.type = this.form.type
        getDictEmnu(params).then(response => {
          this.permissionOptions = response.data;
          console.log(this.permissionOptions)
          this.permissionShow = true;
        });
      }
      if(item.dictValue == 6){
        this.srShow = false;
        this.departShow = true;
        this.permissionShow = false;
      }
      if(item.dictValue == 7){
        this.srShow = true;
        this.departShow = false;
        this.permissionShow = false;
      }
    },
    getPermissionDeflist(){
      getPermissionDeflist().then(response => {
        this.permissionDef = response.data;
        this.permisOptions = response.data;
      });
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getOrgs(){
      getOrgs().then(response => {
        this.orgs = response.data;
      });
    },
    findStoreroom(orgId){
      getSRoomByOrgId({guid: orgId, enable: 1}).then(response => {
        this.storeroomOption = response.data;
      });
    },
    findStoreroom2(orgId){
      getSRoomByOrgId({guid: orgId, enable: 1}).then(response => {
        this.storeroomOption2 = response.data;
      });
    },
    userList(query = '') {
      this.remoteLoading = true;
      listUser({nickName: query}).then(response => {
        this.remoteLoading = false;
        this.userOption = response.rows;
      });
    },
    /** 查询权限管理列表 */
    getList() {
      this.loading = true;
      let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      this.queryParams.srguid && (queryParams.orgid = null);
      listSalespermission(queryParams).then(response => {
        this.salespermissionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        guid: null,
        userId: null,
        permission: null,
        permscope: null,
        type: null,
        status: 0,
        operatorid: null,
        createtime: null,
        lastupdate: null,
        srguid: null,
        deptId: null
      };
       this.srShow = false;
        this.departShow = false;
        this.permissionShow = false;
        this.permissions = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.guid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加权限管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const guid = row.guid || this.ids
      getSalespermission(guid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改权限管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.permissions = this.permissions;
          console.log(this.form.permissions)
          if (this.form.guid != null) {
            updateSalespermission(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSalespermission(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guids = row.guid || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSalespermission(guids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有权限管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSalespermission(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
